/**
 * 
 */
package vashion.azeroth.core.manager.item;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.ExchangeRateConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.MemberErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.item.pojo.ForestPropertyValueDO;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.pojo.ItemYvogueBrandDO;
import vashion.azeroth.core.item.pojo.ItemYvogueForestDO;
import vashion.azeroth.core.item.pojo.PropertyValueDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.manager.forest.BaseForestPropertyManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.yvogue.pojo.YvogueProduct;
import vashion.azeroth.core.yvogue.sftp.SFTPUtil;

/**
 * @author Reganchen on 17/4/26. Yvogue商品写接口
 *
 */
@Service
public class YvogueItemWriteManager {

	private static final String DEFAULT_JPG = "default.jpg";

	private final static Logger log = LoggerFactory.getLogger(YvogueItemWriteManager.class);

	@Autowired
	private BaseItemManager baseItemManager;

	@Autowired
	private BaseItemSkuManager baseItemSkuManager;

	@Autowired
	private ItemWriteManager itemWriteManager;

	@Autowired
	private ItemYvogueBrandManager itemYvogueBrandManager;

	@Autowired
	private ItemYvogueForestManager itemYvogueForestManager;

	@Autowired
	private PersonalMemberManager personalMemberManager;

	@Autowired
	private BaseForestPropertyManager baseForestPropertyManager;

	/**
	 * @param yvogueProduct
	 * @param memberName
	 * @return 保存结果
	 */
	public ApiResult<Boolean> publishItem(YvogueProduct yvogueProduct, String memberName) {
		if (null == yvogueProduct || null == memberName) {
			return ApiResult.newSuccessResult(false);
		}
		// 查找用户
		PersonalMember member = personalMemberManager.getMemberByName(memberName);
		if (null == member) {
			return ApiResult.newErrorResult(MemberErrorEnum.NOT_EXISTID.getErrorCode(),
					MemberErrorEnum.NOT_EXISTID.getErrorMessage());
		}
		// 转换商品
		ItemDO item = this.yvogueProduct2ItemDO(yvogueProduct, member);
		// 如果商品转换不成功，不保存
		if (null == item) {
			return ApiResult.newSuccessResult(false);
		}
		// 查询商品是否存在
		ItemQueryDO itemDoByItemCode = new ItemQueryDO();
		itemDoByItemCode.setItemCode(item.getItemCode());
		itemDoByItemCode.setUserId(member.getMemberId());
		List<ItemDO> itemList = baseItemManager.querySameCodeItem(itemDoByItemCode);
		int totalStock = 0;
		boolean result = false;
		// 如果存在，update商品
		if (null != itemList && itemList.size() == 1) {
			ItemDO itemOrigin = itemList.get(0);
			totalStock = itemOrigin.getStock();
			// 查询商品的property value
			ApiResult<ForestPropertyValueDO> ForestPropertyResult = baseForestPropertyManager
					.getForestPropertyValues(item.getCategoryId(), AzerothConstants.ItemForestProperty.NORMAL);
			if (null != ForestPropertyResult && ForestPropertyResult.isSuccess()
					&& null != ForestPropertyResult.getData()) {
				ForestPropertyValueDO forestPropertyValueDO = ForestPropertyResult.getData();
				List<PropertyValueDO> propertyValueDOListOrigial = forestPropertyValueDO.getPropertyValueDOList();

				for (PropertyValueDO propertyValueDOTemp : item.getFeatureValueDOList()) {
					// 查询商品的property value
					PropertyValueDO propertyValueDO = findSystemPropertyValue(propertyValueDOListOrigial,
							propertyValueDOTemp);
					// 如果数据库中没有对应的尺寸，不保存
					if (null == propertyValueDO)
						continue;
					// 查询出对应的SKU
					ItemSkuDO itemSkuDO = new ItemSkuDO();
					itemSkuDO.setItemId(itemOrigin.getId());
					itemSkuDO.setPropertyValueIdArr(String.valueOf(propertyValueDO.getId()));
					List<ItemSkuDO> itemSkuList = baseItemSkuManager.find(itemSkuDO);
					long originalSkuStock = 0;
					if (null != itemSkuList && itemSkuList.size() == 1) {
						// 有对应的sku，更新sku
						itemSkuDO = itemSkuList.get(0);
						// 更新sku的库存
						originalSkuStock = itemSkuDO.getStock();
						itemSkuDO.setStock(propertyValueDOTemp.getStock());
						result = baseItemSkuManager.update(itemSkuDO) > 0;
					} else if (null == itemSkuList || itemSkuList.size() == 0) {
						// 无对应的sku，新保存sku
						itemSkuDO.setStock(propertyValueDOTemp.getStock());
						itemSkuDO.setUserId(itemOrigin.getUserId());
						itemSkuDO.setStatus(AzerothConstants.Item.NORMAL);
						result = (null != baseItemSkuManager.save(itemSkuDO));
						originalSkuStock = 0;
					} else {
						continue;
					}
					if (result) {
						totalStock = (int) (itemOrigin.getStock() - originalSkuStock + propertyValueDOTemp.getStock());
					}
				}
				// 更新商品的总库存
				ItemDO itemUpdate = new ItemDO();
				itemUpdate.setId(itemOrigin.getId());
				itemUpdate.setStock(totalStock);
				result = itemWriteManager.updateItem(itemUpdate, null, itemOrigin.getUserId()).isSuccess();
			}
		}
		// 如果不存在，save商品
		else if (null == itemList || itemList.size() == 0) {
			List<ItemSkuDO> skuDOList = Lists.<ItemSkuDO>newArrayList();
			// 查询商品的property value
			ApiResult<ForestPropertyValueDO> ForestPropertyResult = baseForestPropertyManager
					.getForestPropertyValues(item.getCategoryId(), AzerothConstants.ItemForestProperty.NORMAL);
			if (null != ForestPropertyResult && ForestPropertyResult.isSuccess()
					&& null != ForestPropertyResult.getData()) {
				ForestPropertyValueDO forestPropertyValueDO = ForestPropertyResult.getData();
				List<PropertyValueDO> propertyValueDOListOrigial = forestPropertyValueDO.getPropertyValueDOList();

				for (PropertyValueDO propertyValueDOTemp : item.getFeatureValueDOList()) {
					// 查询商品的property value
					PropertyValueDO propertyValueDO = findSystemPropertyValue(propertyValueDOListOrigial,
							propertyValueDOTemp);
					// 如果数据库中没有对应的尺寸，不保存
					if (null == propertyValueDO)
						continue;
					// 新建sku
					ItemSkuDO itemSkuDO = new ItemSkuDO();
					itemSkuDO.setStock(propertyValueDOTemp.getStock());
					itemSkuDO.setUserId(member.getMemberId());
					itemSkuDO.setPropertyValueIdArr(String.valueOf(propertyValueDO.getId()));
					itemSkuDO.setStatus(AzerothConstants.Item.NORMAL);
					skuDOList.add(itemSkuDO);
					totalStock = (int) (totalStock + propertyValueDOTemp.getStock());

				}
				// 设置商品的总库存，发布新商品
				item.setStock(totalStock);
				result = itemWriteManager.publishItem(item, skuDOList, null, member.getMemberId()).isSuccess();
			}
		} else {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(result);
	}

	/**
	 * @param propertyValueDOListOrigial
	 * @param propertyValueDOTemp
	 * @return
	 */
	private PropertyValueDO findSystemPropertyValue(List<PropertyValueDO> propertyValueDOListOrigial,
			PropertyValueDO propertyValueDOTemp) {
		PropertyValueDO propertyValueDO = null;
		// 只有一个默认尺寸
		if (StringUtils.isBlank(propertyValueDOTemp.getValue()) || 1 == propertyValueDOListOrigial.size()) {
			propertyValueDO = propertyValueDOListOrigial.get(0);
		} else {
			// 有多个尺寸
			for (PropertyValueDO propertyValueDOOrigialTemp : propertyValueDOListOrigial) {
				if (propertyValueDOOrigialTemp.getValue().equalsIgnoreCase(propertyValueDOTemp.getValue())) {
					propertyValueDO = propertyValueDOOrigialTemp;
				}
			}
		}
		return propertyValueDO;
	}

	/**
	 * @param yvogueProduct
	 * @param member
	 * @return 对应的本系统商品类
	 */
	private ItemDO yvogueProduct2ItemDO(YvogueProduct yvogueProduct, PersonalMember member) {
		ItemDO itemDO = new ItemDO();
		itemDO.setUserId(member.getMemberId());
		itemDO.setMemberName(member.getMemberName());
		itemDO.setFeature(AzerothConstants.Item.ALL.toString());
		// 设置品牌
		ApiResult<ItemYvogueBrandDO> itemYvougeBrandDOResult = itemYvogueBrandManager
				.findByYvogueBrandTitle(yvogueProduct.getBrand());
		if (itemYvougeBrandDOResult.isSuccess() && null != itemYvougeBrandDOResult.getData()) {
			itemDO.setBrandId(itemYvougeBrandDOResult.getData().getBrandId());
			itemDO.setBrandTitle(itemYvougeBrandDOResult.getData().getBrandTitle());
		} else {
			return null;
		}

		// 设置类目
		ApiResult<ItemYvogueForestDO> itemYvoguForestDOResult = itemYvogueForestManager
				.findByYvogueCataTitle(yvogueProduct.getCate());
		if (itemYvoguForestDOResult.isSuccess() && null != itemYvoguForestDOResult.getData()) {
			itemDO.setCategoryId(itemYvoguForestDOResult.getData().getForestId());
			itemDO.setCategoryFullTitle(itemYvoguForestDOResult.getData().getForestTitle());
		} else {
			return null;
		}
		// 设置图片地址
		if (itemYvougeBrandDOResult.isSuccess() && null != itemYvougeBrandDOResult.getData()) {
			StringBuffer mainImgGetURL = new StringBuffer("http://img.yvogue.hk/pimg/pl/")
					.append(itemYvougeBrandDOResult.getData().getYvogueBrandId()).append("/m")
					.append(yvogueProduct.getModel().toLowerCase()).append("/m")
					.append(yvogueProduct.getMaterial().toLowerCase()).append("/c")
					.append(yvogueProduct.getColor().toLowerCase()).append(".jpg");
			itemDO.setPic(mainImgGetURL.toString());
			StringBuffer descImgGetURL = new StringBuffer("http://img.yvogue.hk/pimg/ll/")
					.append(itemYvougeBrandDOResult.getData().getYvogueBrandId()).append("/m")
					.append(yvogueProduct.getModel().toLowerCase()).append("/m")
					.append(yvogueProduct.getMaterial().toLowerCase()).append("/c")
					.append(yvogueProduct.getColor().toLowerCase());
			try {
				String picUrl = SFTPUtil.getProcuctPics(descImgGetURL.toString());
				picUrl = picUrl.substring(picUrl.lastIndexOf('[') + 1, picUrl.lastIndexOf(']')).replaceAll("\"", "");
				String[] picUrlList = picUrl.split(",");
				StringBuffer desPicUrlBuffer = new StringBuffer();
				for (String picUrlTemp : picUrlList) {
					desPicUrlBuffer.append("http://img.yvogue.hk").append(picUrlTemp.trim()).append(",");
				}
				String desPicUrl = desPicUrlBuffer.toString();
				itemDO.setDescPic(desPicUrl);
				// String firstPicUrl = desPicUrl.substring(0,
				// desPicUrl.indexOf(","));
				// itemDO.setPic(firstPicUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		itemDO.setItemCode(yvogueProduct.getPtSku());
		itemDO.setPriceDisplay("0");
		itemDO.setReferencePriceDisplay(yvogueProduct.getPrice().toString());
		itemDO.setPriceCurno(ExchangeRateConstants.CurNos.HKD);
		itemDO.setItemDesc(yvogueProduct.getPtName());
		List<PropertyValueDO> propertyValueDOList = Lists.<PropertyValueDO>newArrayList();
		PropertyValueDO propetyValueDO = new PropertyValueDO();
		propetyValueDO.setValue(yvogueProduct.getSize());
		propetyValueDO.setStock(yvogueProduct.getQuatity().intValue());
		propertyValueDOList.add(propetyValueDO);
		itemDO.setFeatureValueDOList(propertyValueDOList);
		//无图片，商品设置为下架
//		if (itemDO.getDescPic().contains(DEFAULT_JPG)) {
//			itemDO.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
//		} else {
//			itemDO.setStatus(ItemStatusEnum.ORIGIN_STATUS.getStatus());
//		}
		//默认设置为下架
		itemDO.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
		return itemDO;
	}
}
